package com.fumin.service;

import com.fumin.common.RequestHolder;
import com.fumin.dao.SysRoleUserMapper;
import com.fumin.dao.SysUserMapper;
import com.fumin.model.SysRoleAcl;
import com.fumin.model.SysRoleUser;
import com.fumin.model.SysUser;
import com.fumin.util.IpUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * 角色用户service
 * @Author xiayuxuanmin
 * @Date 2019/11/19
 * @Description
 */
@Service
public class SysRoleUserService {

    @Resource
    private SysRoleUserMapper sysRoleUserMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;

    /**
     * 查找具有指定角色的用户集合
     * @param roleId
     * @return
     */
    public List<SysUser> getListByRoleId(int roleId){
        List<Integer> userIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)) {
            return Lists.newArrayList();
        }
       return sysUserMapper.getByIdList(userIdList);
    }

    public void changeRoleUsers(int roleId, List<Integer> userIdList) {
        //获取当前角色原来已经分配的用户的ID集合
        List<Integer> originUserIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)) {
            //没有分配角色的用户
            return;
        }
        //判断原来的用户和现在的用户是否完全一致,如果一致,表示用户没有变化,不用处理
        if(originUserIdList.size() == userIdList.size()){
            HashSet<Integer> originUserIdSet = Sets.newHashSet(originUserIdList);
            HashSet<Integer> userIdSet = Sets.newHashSet(userIdList);
            originUserIdSet.removeAll(userIdSet);
            if (CollectionUtils.isEmpty(originUserIdSet)) {
                //表示权限没有发生改变
                return;
            }
        }
        this.udpateRoleUsers(roleId,userIdList);
        sysLogService.saveRoleUserLog(roleId,originUserIdList,userIdList);
    }

    /**
     * 重新设置角色拥有的权限
     * 为了保持全部成功,或者失败,这里加入事务
     * @param roleId 角色ID
     * @param userIdList 权限点ID集合
     */
    @Transactional
    public void udpateRoleUsers(int roleId,List<Integer> userIdList){
        //清除原有权限
        sysRoleUserMapper.deleteByRoleId(roleId);
        List<SysRoleUser> roleUserList = Lists.newArrayList();
        for (Integer userId : userIdList) {
            SysRoleUser roleUser = SysRoleUser.builder().roleId(roleId).userId(userId)
                    .operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()))
                    .operateTime(new Date()).build();
            roleUserList.add(roleUser);
        }
        //新增新的权限
        sysRoleUserMapper.batchInsert(roleUserList);
    }
}
